package com.axc.gallery2;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.axc.gallery2.dbhelper.ImageInfo;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

/**
 * 工具类
 *
 */
public class Utils extends Activity {
	private static int sTheme;
	public final static int THEME_DEFAULT = 0;
	public final static int THEME_WHITE = 1;
	public final static int THEME_BLUE = 2;

	/**
	 * Set the theme of the Activity, and restart it by creating a new Activity
	 * of the same type.
	 */
	public static void changeToTheme(ListActivity activity, int theme) {
		sTheme = theme;
		activity.finish();
		activity.startActivity(new Intent(activity, activity.getClass()));
	}

	public static void changeToTheme(Activity activity, int theme) {
		sTheme = theme;
		activity.finish();
		activity.startActivity(new Intent(activity, activity.getClass()));
	}

	/** Set the theme of the activity, according to the configuration. */
	public static void onActivityCreateSetTheme(Activity activity) {
		switch (sTheme)  
        { 
        case 1:  
            activity.setTheme(R.style.BlueTheme);   
            break;  
        case 2:  
            activity.setTheme(R.style.WhiteTheme);   
            break;
        case 3:  
            activity.setTheme(R.style.OrangeTheme);   
            break;
        case 4:  
            activity.setTheme(R.style.PinkTheme);   
            break;
        }  
	}
	
	 //导航应用主题样式
    public void setMenuBackGround(LinearLayout linearLayout,int theme){ 
		switch (theme) {
		case R.style.BlueTheme:
			linearLayout.setBackgroundColor(Color.parseColor(String.valueOf("#000000")));
	    break;
		case R.style.OrangeTheme:
			linearLayout.setBackgroundColor(Color.parseColor(String.valueOf("#000000")));
		break;
		case R.style.WhiteTheme:
			linearLayout.setBackgroundColor(Color.parseColor(String.valueOf("#ffffff")));
	    break;
		case R.style.PinkTheme:
			linearLayout.setBackgroundColor(Color.parseColor(String.valueOf("#f779ad")));
		break;
		}
    }
    public void setMenuBackGround(RelativeLayout relativeLayout,int theme){
		switch (theme) {
		case R.style.BlueTheme:
			relativeLayout.setBackgroundColor(Color.parseColor(String.valueOf("#000000")));
	    break;
		case R.style.OrangeTheme:
			relativeLayout.setBackgroundColor(Color.parseColor(String.valueOf("#000000")));
		break;
		case R.style.WhiteTheme:
			relativeLayout.setBackgroundColor(Color.parseColor(String.valueOf("#ffffff")));
	    break;
		case R.style.PinkTheme:
			relativeLayout.setBackgroundColor(Color.parseColor(String.valueOf("#f779ad")));
		break;
		}
    }

	/**
	 * 判断内存卡状态
	 * 
	 * @return
	 */
	public static boolean getExternalStorageState() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 返回一个比屏幕小的Bitmap
	 * 
	 * @param filename
	 * @return
	 */
	public static Bitmap RelBmp(String filename) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(filename, options);
		options.inJustDecodeBounds = false;
		int be = (int) (options.outHeight / (float) 480);
		// 比屏幕小
		if (be < 0)
			be = 1;
		options.inSampleSize = be;// 保持原始比例
		options.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(filename, options);
		return bitmap;
	}

	/**
	 * 从Drawable 得到 Bitmap
	 * 
	 * @param drawable
	 * @return bitmap
	 */

	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
		drawable.getIntrinsicHeight(),
		drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
		: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		// canvas.setBitmap(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
				.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}
	
    public static String uploadFile(String reqUrl, Bundle parameters, String fileParamName,
            String filename, String contentType, byte[] data) {
        HttpURLConnection urlConn = null;
        try {
            urlConn = sendFormdata(reqUrl, parameters, fileParamName, filename, contentType, data);
            String responseContent = read(urlConn.getInputStream());
            return responseContent.trim();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (urlConn != null) {
                urlConn.disconnect();
            }
        }
    }
    
    private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters,
            String fileParamName, String filename, String contentType, byte[] data) {
        HttpURLConnection urlConn = null;
        try {
            URL url = new URL(reqUrl);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setConnectTimeout(5000);// （单位：毫秒）jdk
            urlConn.setReadTimeout(5000);// （单位：毫秒）jdk 1.5换成这个,读操作超时
            urlConn.setDoOutput(true);

            urlConn.setRequestProperty("connection", "keep-alive");
            urlConn.setRequestProperty("Accept-Encoding", "gzip");

            String boundary = "-----------------------------114975832116442893661388290519"; // 分隔符
            urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            boundary = "--" + boundary;
            StringBuffer params = new StringBuffer();
            if (parameters != null) {
                for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
                    String name = iter.next();
                    String value = parameters.getString(name);
                    params.append(boundary + "\r\n");
                    params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
                    // params.append(URLEncoder.encode(value, "UTF-8"));
                    params.append(value);
                    params.append("\r\n");
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.append(boundary);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\""
                    + filename + "\"\r\n");
            sb.append("Content-Type: " + contentType + "\r\n\r\n");
            byte[] fileDiv = sb.toString().getBytes();
            byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes();
            byte[] ps = params.toString().getBytes();

            OutputStream os = urlConn.getOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(os);
            gzipOutputStream.write(ps);
            gzipOutputStream.write(fileDiv);
            gzipOutputStream.write(data);
            gzipOutputStream.write(endData);
            
            os.write(ps);
            os.write(fileDiv);
            os.write(data);
            os.write(endData);
            
            gzipOutputStream.finish();
            os.flush();
            gzipOutputStream.close();
            os.close();
            
            System.out.println("gzip access");

            
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return urlConn;
    }
    
    private static String read(InputStream in) throws IOException {
        /*StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }*/
    	String str = getJsonStringFromGZIP(in);
        in.close();
        return str;
    }
    
	private static String getJsonStringFromGZIP(InputStream in) {
        String jsonString = null;
        try {
            InputStream is = in;
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            // Gzip 流 的前两个字节是 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                //LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
                System.out.println("gzip back!!!");
            } else {
                //LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
            //LogUtil.e("HttpTask", e.toString(),e);
        }
 
        //LogUtil.d("HttpTask", "getJsonStringFromGZIP net output : " + jsonString );
        return jsonString;
    }
 
    private static int getShort(byte[] data) {
        return (int)((data[0]<<8) | data[1]&0xFF);
    }
    
    static List<ImageInfo> PicturesList = new ArrayList<ImageInfo>();

    /**
     * 获取图片
     * 
     * @param strPath 路径
     */
    public static List<ImageInfo> getPictures(final String strPath) {
        // PicturesList可能存放有上一次的结果，有则清空
        if (PicturesList.size() > 0) {
            PicturesList.clear();
        }
        searchPictures(strPath);


        return PicturesList;
    }

    // 遍历文件夹内所有图片（包括子文件夹）：递归调用
    private static void searchPictures(final String strPath) {

        File file = new File(strPath);
        File[] files = file.listFiles();

        if (files == null) {
            return;
        }

        for (int i = 0; i < files.length; i++) {
            final File f = files[i];
            if (f.isFile()) {
                try {
                    int idx = f.getPath().lastIndexOf(".");
                    if (idx <= 0) {
                        continue;
                    }
                    String suffix = f.getPath().substring(idx);
                    if (suffix.toLowerCase().equals(".jpg") ||
                            suffix.toLowerCase().equals(".jpeg") ||
                            suffix.toLowerCase().equals(".bmp") ||
                            suffix.toLowerCase().equals(".png") ||
                            suffix.toLowerCase().equals(".gif")) {
                    	ImageInfo imageInfo=new ImageInfo();
                    	imageInfo.image_id="";
                    	imageInfo.image_path=f.getPath();
                            PicturesList.add(imageInfo);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                searchPictures(f.getPath());
            }
        }
    }
    
    

}
